'use strict';

var _koa = require('koa');

var _koa2 = _interopRequireDefault(_koa);

var _koaSimpleRouter = require('koa-simple-router');

var _koaSimpleRouter2 = _interopRequireDefault(_koaSimpleRouter);

var _co = require('co');

var _co2 = _interopRequireDefault(_co);

var _koaStatic = require('koa-static');

var _koaStatic2 = _interopRequireDefault(_koaStatic);

var _register = require('babel-core/register');

var _register2 = _interopRequireDefault(_register);

var _babelPolyfill = require('babel-polyfill');

var _babelPolyfill2 = _interopRequireDefault(_babelPolyfill);

var _koaSwig = require('koa-swig');

var _koaSwig2 = _interopRequireDefault(_koaSwig);

var _ws = require('ws');

var _ws2 = _interopRequireDefault(_ws);

var _http = require('http');

var _http2 = _interopRequireDefault(_http);

var _https = require('https');

var _https2 = _interopRequireDefault(_https);

var _initController = require('./controllers/initController');

var _initController2 = _interopRequireDefault(_initController);

var _config = require('./config/config');

var _config2 = _interopRequireDefault(_config);

var _latest = require('ssl-root-cas/latest');

var _latest2 = _interopRequireDefault(_latest);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

// default for all https requests 
// (whether using https directly, request, or another module) 
_https2.default.globalAgent.options.ca = _latest2.default.create();
var app = new _koa2.default();

app.context.render = _co2.default.wrap((0, _koaSwig2.default)({
  root: _config2.default.get('viewDir'),
  autoescape: true,
  cache: 'memory', // disable, set to false 
  ext: 'html',
  writeBody: false
}));
_initController2.default.init(app, _koaSimpleRouter2.default);

app.use((0, _koaStatic2.default)(_config2.default.get('staticDir')));

app.use(function (req, res) {
  res.send({ msg: "hello" });
});

var server = _https2.default.createServer(app.callback());
var ws = new _ws2.default('wss://localhost/index/index', {
  origin: 'https://localhost'
});

ws.on('open', function open() {
  console.log('connected');
  ws.send(Date.now());
});

ws.on('close', function close() {
  console.log('disconnected');
});

ws.on('message', function incoming(data, flags) {
  console.log('Roundtrip time: ' + (Date.now() - data) + ' ms', flags);

  setTimeout(function timeout() {
    ws.send(Date.now());
  }, 500);
});
// app.use(async ctx => ctx.body = await ctx.render('index'));
/*
app.use(ctx => {
  ctx.body = 'Hello Koa';
});
*/
server.listen(_config2.default.get('port'), function () {
  console.log('Listening on %d', server.address().port);
});
